<?php


namespace App\Service;

use App\Foundation\Traits\Singleton;
use App\Service\Chat\ChatService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\WebSocketServer\Sender;

class SenderService extends BaseService
{
    use Singleton;

    /**
     * @Inject
     * @var Sender
     */
    protected $sender;

    public function sendToUid($user_id, $cmd, $payload = []): bool
    {
        $fd = ChatService::isOnline($user_id);
        //用户离线不发送
        if (!$fd) {
            return false;
        }
        $this->sender->push((int)$fd, self::formatMsg($cmd, $payload));
        return true;
    }

    public function sendToFd($fd, $cmd, $payload = []): bool
    {
        $this->sender->push((int)$fd, self::formatMsg($cmd, $payload));
        return true;
    }

    public static function formatMsg($cmd, $payload): string
    {
        return json_encode([
            'cmd' => $cmd,
            'payload' => $payload
        ], JSON_UNESCAPED_UNICODE);
    }

    public function debug($fd, $payload)
    {
        $this->sender->push($fd, self::formatMsg('debug', $payload));
    }
}
